package com.srwl.mytx.widget;

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.BottomDialogAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRecord;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.Utils;

import java.math.BigDecimal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class StopLiveDialog extends BottomSheetDialog implements BottomDialogAdapter.OnItemClickListener {

    private static final String TAG = "StopLiveDialog";
    private ImageView iv_avatar;
    private TextView tv_username;
    private TextView tv_audienceSize;
    private TextView tv_rewardAmount;
    private SeekBar sb_donationRote;
    private EditText et_donationAmount;
    private Button btn_commit;
    private View rl_donation;
    private LiveRecord liveRecord;
    private ProgressBar progressBar;
    private RelativeLayout rl_error;
    private TextView tv_error;

    public StopLiveDialog(@NonNull Context context, LiveRecord liveRecord) {
        super(context, R.style.BottomDialog);
        this.liveRecord = liveRecord;
        setContentView(R.layout.stop_live_dialog_layout);
        iv_avatar = findViewById(R.id.iv_avatar);
        tv_username = findViewById(R.id.tv_username);
        tv_audienceSize = findViewById(R.id.tv_audience_size);
        tv_rewardAmount = findViewById(R.id.tv_reward_amount);
        sb_donationRote = findViewById(R.id.sb_donation_rate);
        et_donationAmount = findViewById(R.id.et_donation_amount);
        btn_commit = findViewById(R.id.btn_commit);
        rl_donation = findViewById(R.id.rl_donation);
        progressBar = findViewById(R.id.progress_bar);
        rl_error = findViewById(R.id.rl_error);
        tv_error = findViewById(R.id.tv_error);
        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        if (loginUserInfo != null) {
            //Glide.with(getContext()).load(loginUserInfo.getAvatar()).into(iv_avatar);
            GlideLoadUtils.glideLoad(context, loginUserInfo.getAvatar(), iv_avatar);
            tv_username.setText(loginUserInfo.getUsername());
        }
        tv_audienceSize.setText(liveRecord.getAudienceSize() + "");
        final Double userProfit = liveRecord.getUserProfit();
        tv_rewardAmount.setText(Utils.moneyFormat(userProfit));
        if (userProfit == null) {
            sb_donationRote.setVisibility(View.GONE);
            rl_donation.setVisibility(View.GONE);
        } else {
            sb_donationRote.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    double donationRate = ((Integer) progress).doubleValue() / 100;
                    Log.d(TAG, "progress: " + progress);
                    Log.d(TAG, "onProgressChanged: " + donationRate * userProfit);
                    String donationAmount = Utils.moneyFormat(donationRate * userProfit);
                    if (progress == 0) {
                        et_donationAmount.setText("");
                    } else {
                        if (TextUtils.equals(donationAmount, "0.00")) {
                            et_donationAmount.setText("");
                        } else {
                            et_donationAmount.setText(donationAmount);

                        }
                    }
                    tv_rewardAmount.setText(Utils.moneyFormat(userProfit - Double.valueOf(donationAmount)));
                    CharSequence text = et_donationAmount.getText();
                    if (text instanceof Spannable) {
                        Spannable spanText = (Spannable) text;
                        Selection.setSelection(spanText, text.length());
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            MoneyInputCheck moneyInputCheck = new MoneyInputCheck(getContext(), -0.01, userProfit, new MoneyInputCheck.InteractionListener() {
                @Override
                public void showErrorMessage(String message) {
                    //showToast(et_donationAmount, message);
                    tv_error.setText(message);
                    rl_error.setVisibility(View.VISIBLE);
                }

                @Override
                public void waitInput() {
                    rl_error.setVisibility(View.INVISIBLE);
                    tv_rewardAmount.setText(Utils.moneyFormat(userProfit));
                }

                @Override
                public void inputRight() {
                    rl_error.setVisibility(View.INVISIBLE);
                    String amountString = et_donationAmount.getText().toString();
                    if (!TextUtils.isEmpty(amountString)) {
                        tv_rewardAmount.setText(Utils.moneyFormat(userProfit - Double.valueOf(amountString)));
                    }
                }
            });

            et_donationAmount.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    moneyInputCheck.onTextChanged(s);
                }

                @Override
                public void afterTextChanged(Editable s) {
                    moneyInputCheck.afterTextChanged(s);
                }
            });
        }


        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Helper.getInstance().isNetworkConnected()) {
                    ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
                    return;
                }
                btn_commit.setEnabled(false);
                if (liveRecord.getUserProfit() == null) {

                    dismiss();
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    LiveRecord updateLiveRecord = new LiveRecord();
                    updateLiveRecord.setId(liveRecord.getId());
                    updateLiveRecord.setrId(liveRecord.getrId());
                    String amountString = et_donationAmount.getText().toString();
                    if (!TextUtils.isEmpty(amountString)) {
                        updateLiveRecord.setDonationAmount(Double.valueOf(amountString));
                    }
                    RetrofitManager.getInstance().createRequest(LiveService.class)
                            .handleLiveProfit(updateLiveRecord)
                            .enqueue(new Callback<CommonResult>() {
                                @Override
                                public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                    progressBar.setVisibility(View.GONE);
                                    CommonResult result = response.body();
                                    if (!response.isSuccessful() || result == null) {
                                        Log.e(TAG, "onResponse: " + response.message());
                                        btn_commit.setEnabled(true);
                                        showToast(btn_commit, getContext().getString(R.string.system_busy));
                                        return;
                                    }

                                    if (result.isError()) {
                                        Log.e(TAG, "onResponse: " + result.getMsg());
                                        btn_commit.setEnabled(true);
                                        showToast(btn_commit, getContext().getString(R.string.system_busy));

                                        return;
                                    }
                                    btn_commit.setEnabled(false);
                                    Log.d(TAG, "onResponse: 直播结算完成");
                                    showToast(btn_commit, "直播结算完成,收益已入账至钱包余额");
                                    btn_commit.postDelayed(() -> dismiss(), 2500);

                                    //   btn_commit.postDelayed(StopLiveDialog.this::dismiss, 2000);
                                    if (result.getData() != null) {
                                        BigDecimal balance = (BigDecimal) result.getData();
                                        UserProfileManager.getInstance().setUserBalance(balance.doubleValue());
                                    }

                                }

                                @Override
                                public void onFailure(Call<CommonResult> call, Throwable t) {
                                    Log.e(TAG, "onFailure: " + t.getMessage());
                                    progressBar.setVisibility(View.GONE);
                                    btn_commit.setEnabled(true);

                                }
                            });
                }
            }
        });
    }

    private void showToast(View view, String message) {
        Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
    }


    @Override
    public void onClick(int position) {

    }

    @Override
    public void onCancel() {
        dismiss();
    }

    public interface InteractionListener {
        void onDialogItemViewClick(int position, String itemName);
    }
}
